<template>
  <div>
    <el-form ref="elForm" size="medium" label-width="100px">
      <el-upload
        accept=".xlsx"
        ref="upload"
        multiple
        :limit="5"
        action="/result/materi/importMateri"
        :on-preview="handlePreview"
        :on-change="handleChange"
        :on-remove="handleRemove"
        :on-exceed="handleExceed"
        :file-list="fileList"
        :http-request="excelUpload"
        :auto-upload="false"
      >
        <el-button slot="trigger" size="small" type="primary"
          >选取文件</el-button
        >
        <el-button
          style="margin-left: 133px"
          size="small"
          type="success"
          @click="submitUpload"
          >上传到服务器
        </el-button>
        <div slot="tip" class="el-upload__tip">
          只能上传xlsx文件，且不超过100m
        </div>
      </el-upload>
    </el-form>
  </div>
</template>
<script>
import { uploadHospital, getImportLog } from "@/api/materi/materi";
import request from "@/utils/request";
var rLoading = null;
export default {
  name: "importmateriapply",
  inheritAttrs: false,
  components: {},
  props: [],
  data() {
    return {
      fileData: "", // 文件上传数据（多文件合一）
      fileList: [], // upload多文件数组
      uploadData: {
        fieldData: {
          id: "", // 机构id,
        },
      },
    };
  },
  computed: {},
  watch: {},
  created() {},
  mounted() {},
  methods: {
    // 上传前对文件的大小的判断
    beforeUpload(file) {
      const extension = file.name.split(".")[1] === "xls";
      const extension2 = file.name.split(".")[1] === "xlsx";
      const isLt50M = file.size / 1024 / 1024 < 50;
      if (!extension && !extension2) {
        this.$message.error("导入文件只支持xls和xlsx文件");
        this.$refs["importFileUploader"].clearFiles();
      }
      if (!isLt50M) {
        this.$message.error("导入文件小于50M");
        this.$refs["importFileUploader"].clearFiles();
      }
      if ((extension || extension2) && isLt50M) {
        return this.importfxx(file).then(function (result) {
          if (!result) {
            return false;
          } else {
            return true;
          }
        });
      }
    },

    handleUploadSuccess: function (response, file, fileList) {
      if (response.code === "0-0-0-0-0-0") {
        this.$message({
          message: "导入成功",
          type: "info",
        });
        // ...
      } else {
        this.$message({
          message: response.message,
          type: "error",
        });
      }
    },
    excelUpload(fileList) {
      uploadHospital(fileList);
    },
    openLoading() {
      const loading = this.$loading({
        // 声明一个loading对象
        lock: true, // 是否锁屏
        text: "正在加载...", // 加载动画的文字
        spinner: "el-icon-loading", // 引入的loading图标
        background: "rgba(0, 0, 0, 0.3)", // 背景颜色
        target: ".sub-main", // 需要遮罩的区域
        body: true,
        customClass: "mask", // 遮罩层新增类名
      });
      setTimeout(function () {
        // 设定定时器，超时5S后自动关闭遮罩层，避免请求失败时，遮罩层一直存在的问题
        loading.close(); // 关闭遮罩层
      }, 10000);
      return loading;
    },

    startCheckLog(importGuid) {
      var param = {};
      let that = this;
      param.importGuid = importGuid;
      var interval = null; //计时器
      var outTimes = 5;
      var currTimes = 0;
      rLoading = this.openLoading();
      interval = self.setInterval(function () {
        currTimes = currTimes + 1;
        if (currTimes <= 5) {
          getImportLog(param).then((response) => {
            if (response.code === 200) {
              console.log(response);
              if (
                response &&
                response.data &&
                response.data.fstatus == "sta_success"
              ) {
                that.$message({
                  message: response.data.fimportlog,
                  type: "success",
                });
                self.clearInterval(interval);
                rLoading.close();
                that.$emit("materiApplyListSearch","");
              } else if (
                response &&
                response.data &&
                response.data.fstatus == "sta_error"
              ) {
                that.$message({
                  message: response.data.fimportlog,
                  type: "error",
                });
                self.clearInterval(interval);
                rLoading.close();
                that.$emit("materiApplyListSearch","");
              }
            } else {
              self.clearInterval(interval);
              rLoading.close();
              that.$message({
                message: response.msg,
                type: "error",
              });
              that.$emit("materiApplyListSearch","");
            }
          });
        }else{
          self.clearInterval(interval);
        }
      }, 5000);
    },

    // 上传到服务器
    submitUpload() {
      let fieldData = this.uploadData.fieldData; // 缓存，注意，fieldData不要与fileData看混
      let that = this;
      if (this.fileList.length === 0) {
        this.$message({
          message: "请先选择文件",
          type: "warning",
        });
      } else {
        const isLt100M = this.fileList.every(
          (file) => file.size / 1024 / 1024 < 100
        );
        if (!isLt100M) {
          this.$message.error("请检查，上传文件大小不能超过100MB!");
        } else {
          //   uploadHospital(this.fileList);
          that.fileData = new FormData(); // new formData对象
          if (that.fileList.length > 0) {
            that.fileList.forEach(function (file) {
              that.fileData.append("questionExcels", file.raw);
              that.fileData.append("uploadPsn", that.$store.state.user.name);
            });
          } else {
            that.$message.warning("当前没有合适文件可以上传");
          }
          uploadHospital(that.fileData).then((response) => {
            if (response.code === 200) {
              that.$message({
                message: response.msg,
                type: "success",
              });
              that.fileList = [];
              that.startCheckLog(response.data);
            } else {
              that.$message({
                message: response.msg,
                type: "error",
              });
            }
          });
          // post(
          //   this.baseUrlData.url_02 + ":8090/personality/uploadExcel",
          //   this.fileData
          // ).then((response) => {
          //   if (response.data.code === 0) {
          //     this.$message({
          //       message: "上传成功",
          //       type: "success",
          //     });
          //     this.fileList = [];
          //   } else {
          //     this.$message({
          //       message: response.data.desc,
          //       type: "error",
          //     });
          //   }
          // });
        }
      }
    },
    handlePreview() {},
    //移除
    handleRemove(file, fileList) {
      this.fileList = fileList;
      // return this.$confirm(`确定移除 ${ file.name }？`);
    },

    // 选取文件超过数量提示
    handleExceed(files, fileList) {
      this.$message.warning(
        `当前限制选择 5 个文件，本次选择了 ${files.length} 个文件，共选择了 ${
          files.length + fileList.length
        } 个文件`
      );
    },

    //监控上传文件列表
    handleChange(file, fileList) {
      let existFile = fileList
        .slice(0, fileList.length - 1)
        .find((f) => f.name === file.name);
      if (existFile) {
        this.$message.error("当前文件已经存在!");
        fileList.pop();
      }
      this.fileList = fileList;
    },
  },
};
</script>
<style>
.el-upload__tip {
  line-height: 1.2;
}
</style>